package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thingsboard.server.common.data.Tenant;
import org.thingsboard.server.common.data.User;

import lombok.extern.slf4j.Slf4j;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysCompanyThingsboard;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.mapper.SysCompanyThingsboardMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.FileService;
import com.ruoyi.system.service.ISysCompanyThingsboardService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IThingsBoardService;
import com.ruoyi.system.service.IThingsBoardTenantService;

/**
 * 部门管理 服务实现
 * 
 * @author ruoyi
 */
@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Slf4j
@Service
public class SysDeptServiceImpl implements ISysDeptService
{
    @Value("${tb.inject.ruleChain.name:rc-root-cg}")
    private String injectRuleChainName;

    @Value("${tb.inject.ruleChain.filename:rc-root-cg.json}")
    private String injectRuleChainFilename;

    @Value("${tb.inject.deviceProfile.mqtt.name:dp-mqtt-cg}")
    private String injectMqttDeviceProfileName;

    @Value("${tb.inject.deviceProfile.mqtt.filename:dp-mqtt-cg.json}")
    private String injectMqttDeviceProfileFilename;

    @Value("${tb.inject.deviceProfile.http.name:dp-http-cg}")
    private String injectHttpDeviceProfileName;

    @Value("${tb.inject.deviceProfile.http.filename:dp-http-cg.json}")
    private String injectHttpDeviceProfileFilename;

    @Value("${tb.inject.deviceProfile.coap.name:dp-coap-cg}")
    private String injectCoapDeviceProfileName;

    @Value("${tb.inject.deviceProfile.coap.filename:dp-coap-cg.json}")
    private String injectCoapDeviceProfileFilename;

    @Value("${tb.inject.deviceProfile.lwm2m.name:dp-lwm2m-cg}")
    private String injectLwm2mDeviceProfileName;

    @Value("${tb.inject.deviceProfile.lwm2m.filename:dp-lwm2m-cg.json}")
    private String injectLwm2mDeviceProfileFilename;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysRoleMapper roleMapper;
    
    @Autowired
    private SysUserMapper userMapper;
    
    @Autowired
    private IThingsBoardService thingsboardService;
    
    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private SysCompanyThingsboardMapper companyThingsboardMapper;

    @Autowired
    private IThingsBoardTenantService thingsBoardTenantService;

    //客户角色Id
    @Value("${sysUser.customerRoleId:105}")
    private Long customerRoleId;
    //产品管理员角色Id
    @Value("${sysUser.commonRoleId:2}")
    private Long commonRoleId;

    /**
     * 查询部门管理数据
     * 
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept, SysDept currentDept, Boolean flag)
    {
        if (currentDept != null){
            Long deptId = currentDept.getDeptId();
            boolean customerFlag = checkIsCustomer(deptId);
            if (customerFlag){
                Long customerId = getCustomerId(deptId);
                dept.setCustomerDeptId(customerId);
            }
        }
        List<SysDept> sysDepts = deptMapper.selectDeptList(dept);
        if (currentDept == null || flag){
            return sysDepts;
        }
        //进行过滤
        Long topParentId = null;
        Long parentId = currentDept.getParentId();
        if (parentId == 0L){
            topParentId = currentDept.getDeptId();
        }else {
            List<String> trim = StrUtil.splitTrim(currentDept.getAncestors(), ",");
            topParentId = cn.hutool.core.convert.Convert.toLong(trim.get(1));
        }
        List<SysDept> result = new ArrayList<>();
        for (SysDept sysDept : sysDepts) {
            if (sysDept.getDeptId().equals(topParentId) || sysDept.getParentId().equals(topParentId) || StrUtil.splitTrim(sysDept.getAncestors(),",").contains(cn.hutool.core.convert.Convert.toStr(topParentId))){
                result.add(sysDept);
            }
        }
        return result;
    }

    /**
     * 构建前端所需要树结构
     * 
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts)
    {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDept dept : depts)
        {
            tempList.add(dept.getDeptId());
        }
        for (Iterator<SysDept> iterator = depts.iterator(); iterator.hasNext();)
        {
            SysDept dept = (SysDept) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     * 
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts)
    {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     * 
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Integer> selectDeptListByRoleId(Long roleId)
    {
        SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }
    
    /**
     * 根据用户id查询公司id
     * 
     * @param userId 用户id
     * @return 公司id
     */
    @Override
    public Long selectCompanyIdByUserId(Long userId) {
    	SysUser user = userMapper.selectUserById(userId);
    	return selectCompanyIdByUser(user);
    }
    
    /**
     * 根据用户查询公司id
     * 
     * @param userId 用户id
     * @return 公司id
     */
    @Override
    public Long selectCompanyIdByUser(SysUser user) {
    	SysDept userDept = deptMapper.selectDeptById(user.getDeptId());
    	long companyId = userDept.getParentId()==0L ? 
        		userDept.getDeptId().longValue():
        		Long.parseLong(userDept.getAncestors().split(",")[1]);
        return companyId;
    }

    /**
     * 根据部门ID查询信息
     * 
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId)
    {
        return deptMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     * 
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId)
    {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在子节点
     * 
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId)
    {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0 ? true : false;
    }

    /**
     * 查询部门是否存在用户
     * 
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId)
    {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0 ? true : false;
    }

    /**
     * 校验部门名称是否唯一
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept)
    {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    private JSONObject InjectTbTemplate(SysCompanyThingsboard sysCompanyThingsboard) {
        JSONObject deviceProfileIds = new JSONObject();
        String content = FileService.load("/thingsboard/rulechain/" + injectRuleChainFilename, false);
        String ruleChainId = thingsBoardTenantService.importRuleChainEx(injectRuleChainName, content, sysCompanyThingsboard);
        content = FileService.load("/thingsboard/deviceprofile/" + injectMqttDeviceProfileFilename, false);
        deviceProfileIds.put("MQTT", thingsBoardTenantService.importDeviceProfileEx(injectMqttDeviceProfileName, content, ruleChainId, sysCompanyThingsboard));
        content = FileService.load("/thingsboard/deviceprofile/" + injectHttpDeviceProfileFilename, false);
        deviceProfileIds.put("HTTP", thingsBoardTenantService.importDeviceProfileEx(injectHttpDeviceProfileName, content, ruleChainId, sysCompanyThingsboard));
        content = FileService.load("/thingsboard/deviceprofile/" + injectCoapDeviceProfileFilename, false);
        deviceProfileIds.put("CoAP", thingsBoardTenantService.importDeviceProfileEx(injectCoapDeviceProfileName, content, ruleChainId, sysCompanyThingsboard));
        content = FileService.load("/thingsboard/deviceprofile/" + injectLwm2mDeviceProfileFilename, false);
        deviceProfileIds.put("LwM2M", thingsBoardTenantService.importDeviceProfileEx(injectLwm2mDeviceProfileName, content, ruleChainId, sysCompanyThingsboard));
        return deviceProfileIds;
    }
    /**
     * 新增保存部门信息
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDept(SysDept dept)
    {
    	// 如果父节点parentId等于0,即为新增公司
    	if(dept.getParentId()==0L) {
    		dept.setAncestors(String.valueOf(dept.getParentId()));
    		
    		int rows = deptMapper.insertDept(dept);
    		if(1==rows) {
    			//借用checkDeptNameUnique方法返回新增公司的信息
    			SysDept newDept = deptMapper.checkDeptNameUnique(dept.getDeptName(), 0L);
    			//自动创建公司管理员用户，用户昵称=公司名称， 用户名称="admin"+deptId
    			SysUser user = new SysUser();
    			user.setUserName("admin"+newDept.getDeptId().longValue());
    			user.setNickName(newDept.getDeptName());
    			user.setPhonenumber(dept.getPhone());
    			user.setEmail(newDept.getEmail());
    			user.setCreateBy(SecurityUtils.getUsername());
    			user.setPassword(SecurityUtils.encryptPassword("12345678"));
    			user.setDept(newDept);
    			user.setDeptId(newDept.getDeptId());
    			Long[] roleids = {3L}; //3 = 公司管理员
    			user.setRoleIds(roleids);
    			userService.insertUser(user);
    			//自动创建thingsboard租户，租户名称(title)=公司名称
    			Tenant tenant = thingsboardService.addNewTenant(dept.getDeptName());
    			//自动创建thingsboard租户用户账号，租户用户账号(email)=公司email, 租户用户账号密码=随机数(可以重复)
    			String tenantUserPassword = genRandomPassword(8);
    			User tenantUser = thingsboardService.addNewTenantUser(tenant, user.getUserName()+"@hanyunplat.com", tenantUserPassword);
    			//保存公司与thingsboard关联表
    			SysCompanyThingsboard companyThingsboard = new SysCompanyThingsboard();
    			companyThingsboard.setCompanyId(newDept.getDeptId());
    			companyThingsboard.setCompanyName(newDept.getDeptName());
    			companyThingsboard.setTbTenantId(tenant.getId().getId().toString());
    			companyThingsboard.setTbTenantTitle(tenant.getTitle());
    			companyThingsboard.setTbUserId(tenantUser.getId().getId().toString());
    			companyThingsboard.setTbUsername(tenantUser.getEmail());
    			companyThingsboard.setTbPassword(tenantUserPassword);
                JSONObject deviceProfileIds = InjectTbTemplate(companyThingsboard);
                companyThingsboard.setTbMqttDeviceProfileId(deviceProfileIds.getString("MQTT"));
                companyThingsboard.setTbHttpDeviceProfileId(deviceProfileIds.getString("HTTP"));
                companyThingsboard.setTbCoapDeviceProfileId(deviceProfileIds.getString("CoAP"));
                companyThingsboard.setTbLwm2mDeviceProfileId(deviceProfileIds.getString("LwM2M"));
    			companyThingsboardMapper.insertSysCompanyThingsboard(companyThingsboard);
    		}
    		return rows;
    	}
    	else {
    		SysDept info = deptMapper.selectDeptById(dept.getParentId());
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
            {
                throw new CustomException("部门停用，不允许新增");
            }
            dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
            //客户公司，验证所有父部门是否是客户公司
            if (dept.getIsCustomer() == 1){
                checkIsCustomer(dept.getAncestors());
            }
            return deptMapper.insertDept(dept);
    	}
    }


    public int systestDept(){
        SysCompanyThingsboard b=new SysCompanyThingsboard();
        b.setCompanyId(348L);
        List<SysCompanyThingsboard> list = companyThingsboardMapper.selectSysCompanyThingsboardList(b);
        if(CollectionUtil.isNotEmpty(list)){
            list.forEach(item -> {
                //自动创建thingsboard租户，租户名称(title)=公司名称
                Tenant tenant = thingsboardService.addNewTenant(item.getCompanyName());
                User tenantUser = thingsboardService.addNewTenantUser(tenant, item.getTbUsername(), item.getTbPassword());
                //保存公司与thingsboard关联表
                JSONObject deviceProfileIds = InjectTbTemplate(item);
                item.setTbMqttDeviceProfileId(deviceProfileIds.getString("MQTT"));
                item.setTbHttpDeviceProfileId(deviceProfileIds.getString("HTTP"));
                item.setTbCoapDeviceProfileId(deviceProfileIds.getString("CoAP"));
                item.setTbLwm2mDeviceProfileId(deviceProfileIds.getString("LwM2M"));
                companyThingsboardMapper.updateSysCompanyThingsboard(item);
            });
        }
        return 0;
    }


    /**
     * 验证所有父部门是否是客户公司
     *
     * @param ancestors
     */
    private void checkIsCustomer(String ancestors){
        List<String> deptIdList = StrUtil.splitTrim(ancestors, ",");
        if (CollUtil.isEmpty(deptIdList)){
            return;
        }
        for (int i = deptIdList.size() - 1; i > 0; i--) {
            String deptId = deptIdList.get(i);
            SysDept sysDept = deptMapper.selectDeptById(Convert.toLong(deptId));
            if (sysDept.getIsCustomer() == 1){
                throw new CustomException("添加失败！该部门的上级部门中已存在客户部门");
            }
        }
    }
    
    /**
     * 生成随机密码
     * @param length 密码长度
     * @return 密码
     */
    private String genRandomPassword(int length) {
    	char dex[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
    				  'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
    				  '0','1','2','3','4','5','6','7','8','9','!','@','#','$','%','^','&','*','(',')','{','}','[',']','|','?'};
    	java.util.Random rand = new java.util.Random();
    	StringBuffer pw = new StringBuffer();
    	for(int i = 0; i<length; i++) {
    		pw.append(dex[rand.nextInt(dex.length)]);
    	}
    	return pw.toString();
    }

    /**
     * 修改保存部门信息
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(SysDept dept)
    {
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
        //修改为客户公司
        if (dept.getIsCustomer() == 1){
            checkIsCustomer(oldDept.getAncestors());
        }
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     * 
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept)
    {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        deptMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     * 
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     * 
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId)
    {
        return deptMapper.deleteDeptById(deptId);
    }

    @Override
    public void setLogo(Long deptId, String logo) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<SysRole> sysRoles = loginUser.getUser().getRoles();
        if (CollUtil.isEmpty(sysRoles)){
            throw new CustomException("当前用户未分配角色");
        }
        SysRole sysRole = sysRoles.get(0);
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        if (sysDept == null){
            throw new CustomException("没有查询到当前部门信息");
        }
        //产品管理员
        if (sysRole.getRoleId().compareTo(commonRoleId) == 0){
            if (sysDept.getParentId() == 0L){
                sysDept.setLogo(logo);
                deptMapper.updateDept(sysDept);
            }else {
                String deptIdStr = StrUtil.splitTrim(sysDept.getAncestors(), ",").get(1);
                Long id = Convert.toLong(deptIdStr);
                SysDept dept = deptMapper.selectDeptById(id);
                dept.setLogo(logo);
                deptMapper.updateDept(dept);
            }
        }
        //客户管理员
        if (sysRole.getRoleId().compareTo(customerRoleId) == 0){
            //当前部门
            if (sysDept.getIsCustomer() == 1){
                sysDept.setLogo(logo);
                deptMapper.updateDept(sysDept);
                return;
            }
            List<String> deptIds = StrUtil.splitTrim(sysDept.getAncestors(), ",");
            //从第二个部门id开始
            boolean flag = false;
            for (int i = 1; i < deptIds.size(); i++) {
                String deptIdStr = deptIds.get(i);
                Long id = Convert.toLong(deptIdStr);
                SysDept dept = deptMapper.selectDeptById(id);
                if (dept.getIsCustomer() == 1){
                    dept.setLogo(logo);
                    deptMapper.updateDept(dept);
                    flag = true;
                    break;
                }
            }
            //该客户没有挂在客户公司下面
            if (!flag){
                throw new CustomException("当前用户未绑定客户公司");
            }
        }
    }

    @Override
    public Map<String,String> getLogo(Long deptId) {
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        if (sysDept == null){
            throw new CustomException("没有查询到当前部门信息");
        }
        //判断当前部门是公司还是客户公司
        if (sysDept.getIsCustomer() == 1 || sysDept.getParentId() == 0L){
            Map<String,String> result = new HashMap<>();
            result.put("logo",sysDept.getLogo());
            return result;
        }
        List<String> deptIds = StrUtil.splitTrim(sysDept.getAncestors(), ",");
        for (int i = deptIds.size() - 1; i > 0 ; i--) {
            Long id = Convert.toLong(deptIds.get(i));
            SysDept dept = deptMapper.selectDeptById(id);
            if (dept.getIsCustomer() == 1){
                Map<String,String> result = new HashMap<>();
                result.put("logo",dept.getLogo());
                return result;
            }
        }
        //当前部门属于公司，不属于客户公司
        String id = StrUtil.splitTrim(sysDept.getAncestors(), ",").get(1);
        SysDept dept = deptMapper.selectDeptById(Convert.toLong(id));
        Map<String,String> result = new HashMap<>();
        result.put("logo",dept.getLogo());
        return result;
    }

    @Override
    public SysDept lookupByName(String name, Long companyId) {
        SysDept sysDept = deptMapper.selectDeptByName(name, companyId);
        return sysDept;
    }

    @Override
    public boolean checkIsCustomer(Long deptId) {
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        if (sysDept == null) {
            throw new CustomException("当前用户所属组织不存在！");
        }
        if (sysDept.getIsCustomer() == 1) {
            return true;
        }
        if (sysDept.getParentId() == 0){
            return false;
        }
        List<String> deptIds = StrUtil.splitTrim(sysDept.getAncestors(), ",");
        for (int i = deptIds.size() - 1; i > 0; i--) {
            String deptIdStr = deptIds.get(i);
            SysDept dept = deptMapper.selectDeptById(Convert.toLong(deptIdStr));
            if (dept.getIsCustomer() == 1) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Long getCustomerId(Long deptId) {
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        if (sysDept == null) {
            throw new CustomException("当前用户所属组织不存在！");
        }
        if (sysDept.getIsCustomer() == 1){
            return sysDept.getDeptId();
        }
        List<String> deptIds = StrUtil.splitTrim(sysDept.getAncestors(), ",");
        for (int i = deptIds.size() - 1; i > 0; i--) {
            String deptIdStr = deptIds.get(i);
            SysDept dept = deptMapper.selectDeptById(Convert.toLong(deptIdStr));
            if (dept.getIsCustomer() == 1) {
                return dept.getDeptId();
            }
        }
        return null;
    }

    @Override
    public Long getTopDeptId(Long deptId) {
        boolean flag = checkIsCustomer(deptId);
        if (flag){
            return getCustomerId(deptId);
        }
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        List<String> deptIds = StrUtil.splitTrim(sysDept.getAncestors(), ",");
        return sysDept.getParentId() == 0L ? sysDept.getDeptId(): cn.hutool.core.convert.Convert.toLong(deptIds.get(1));
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t)
    {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
